 var appPath = getAppPath();

$(function(){
	// 尺寸
	$("#editPpSize").combobox({
		url:appPath+'/itbPrintPara/getSizeInfoForCombo.action',
		valueField:'size_id',
		textField:'comboShow',
		onSelect:function(row){
			// TODO
		}
	});
	
	initJspGrid();
	initUploader();
});

// 样版列表初始化
function initJspGrid(){
	
	$('#printGrid').datagrid({
	    url:appPath + "/itbPrintPara/getPrintParaInfoPg.action",
	    height:'full',
	    //remoteSort:false,
	    striped:true,
	    fitColumns:true,
	    queryParams: getQueryParam(),
	    singleSelect:false,
	    // If set to true, clicking a checkbox will always select the row. 
	    // If false, selecting a row will not check the checkbox.
	    selectOnCheck:true,
	    // If true, the checkbox is checked/unchecked when the user clicks on a row. 
	    // If false, the checkbox is only checked/unchecked when the user clicks exactly on the checkbox.
	    checkOnSelect:true,
	    frozenColumns:[[
	        {field:'ck',checkbox:'true',width:10,align:'center',sortable:false}
	    ]],
	    columns:[[
  	        {field:'pp_id',title:'套餐ID',width:35,align:'center',sortable:false},
  	        {field:'pp_name',title:'套餐名称',width:40,align:'center',sortable:false},
  	        {field:'name',title:'内部名称',width:60,align:'center',sortable:false},
	        {field:'type',title:'分类',width:40,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.pp_id) return "N/A";
	        		var type = '<span style="color:red">未知</span>';
	        		switch(Number(value||'0')){
	        			case 1: type='<span style="color:red">印刷用</span>'; break;
	        			case 2: type='<span style="color:blue">配件用</span>'; break;
	        			case 3: type='<span style="color:green">虚拟商品用</span>'; break;
	        			case 10: type='<span style="color:green">LOGO商品用</span>'; break;
	        			case 11: type='<span style="color:green">营销商品用</span>'; break;
	        		}
	        		return type;
	        	}
		    },
  	        {field:'desc',title:'印刷套餐详情 [点击查看]',width:120,align:'left',sortable:false,
	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.pp_id) return "N/A";
	        		//var show = '[点击查看]';
	        		if(rowData.desc && rowData.desc.length>0){
	        			if(rowData.desc.length>16){
	        				show = rowData.desc.substr(0,15)+'...';
	        			}else{
	        				show = rowData.desc;
	        			}
	        		}
	        		return "<a href='javascript:void(0)' onClick='showDetail("+rowData.pp_id+")'>"+show+"</a>";
	        	}
		    },
	        {field:'state',title:'状态',width:40,align:'center',sortable:false,
  	        	formatter:function(value, rowData, rowIndex){
	        		if(!rowData.pp_id) return "N/A";
	        		var show = getState4Show(value);
	        		return "<a href='javascript:void(0)' onClick='editState("+rowData.pp_id+")'>"+show+"</a>";
	        	}
		    },
	        {field:'size_id',title:'尺寸ID',width:35,align:'center',sortable:false},
	        {field:'style',title:'样式',width:35,align:'center',sortable:false},
	        {field:'mat',title:'材质',width:35,align:'center',sortable:false},
	        {field:'tech',title:'工艺',width:35,align:'center',sortable:false},
	        {field:'thumbs',title:'缩略图',width:35,align:'center',sortable:false},
	        {field:'create_time',title:'创建时间',width:45,align:'center',sortable:false},
	        {field:'update_time',title:'更新时间',width:45,align:'center',sortable:false}	        
	    ]],
	    hideColumn:['user_type'],
	    //view: imgView,// 自定义View
	    pagination:true,
		rownumbers:true,
		toolbar:[
			{
				text:'新建印刷套餐',
				iconCls:'icon-add',
				handler:function(){
					addPrintPara();
				}
			},
			/*{
				text:'删除印刷套餐',
				iconCls:'icon-cancel',
				handler:function(){
					delPrintPara();
				}
			}			
			,{
				text:'下载',
				iconCls:'icon-cancel',
				handler:function(){
				downloadPrintPara();
					
				}
			}*/
		]
	});
}

function getState4Show(value){
	var state = '<span style="color:red">未知</span>';
	switch(Number(value||'0')){
		case 10: state='<span style="color:green">有效</span>'; break;
		case 20: state='<span style="color:red">无效</span'; break;
	}
	return state;
}


//印刷状态   编辑
function editState(ppIds){
	$("#stateDlg").show();
	$('#stateForm').form('clear');
	$("#updPpNo").html('');

	$("#updPpId").val(ppIds);
	
	var title = '印刷参数状态';
	var url = appPath + "/itbPrintPara/getPrintParaInfoLst.action?pp_id="+ ppIds;
	$.get(url,function(ret){
		if (ret && ret.length>0){
			var info = ret[0];
			$("#updPpNo").html(info.pp_id||'');
			$("#updPpState").combobox('select',info.state||0);
		}
	});
	
	$("#stateBtn").show();
	$('#stateDlg').window({
		title: title,
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#stateDlg').window('move',{top:20,left:20});
	$('#stateDlg').window('open');
}
function cancelUpdState(){
	$('#stateDlg').window('close');
}
function doUpdState(){
	var id = $("#updPpId").val();
	var state = $("#updPpState").combobox('getValue');
	
	// 默认更新印刷状态
	var url = appPath+"/itbPrintParaWeb/updPrintPara.action";
	var sendData = {
		"printParaInfo.pp_id": Number(id||"0"),
		"printParaInfo.state": Number(state || "0"),
	};
	
  $.post(url, sendData, function(data){  
		if (data == "ok") { 
			$.messager.alert('提示信息','更新成功','info');
			$('#stateDlg').window('close');
			doQuery();			
      } else {
      	$.messager.alert('提示信息','更新失败','info');
      }
  });
}


//上传印刷图片
var EDIT_IMG_IDX = 0;
function initUploader(){
	var url = "http://upload.itbour.com/upload/user?device=101&user_type=0&user_id="+(g_userId||0);
    var option = {};
    option.id = 'selImgFile';
    option.url = url;
    option.callback = function(res){
    	if(!res.success){
    		alert(res.msg);
            return;
    	}
    	if(res && res.data && res.data.url && res.data.url.length>0){
    		EDIT_IMG_IDX = Number(EDIT_IMG_IDX||0)+1;
    		
    		var showImg = res.data.url+'?x-oss-process=image/resize,m_pad,h_180,w_180,color_cccccc';
			var imgHtml = '<div style="margin:8px;" id="editImg_'+EDIT_IMG_IDX+'">'+
				'<a href="' + res.data.url + '" target="_blank" class="editImgUrl" style="margin-right:10px;">'+
				'<img src="'+showImg+'" style="display:inline;height:100px;width:100px">'+
				'</a>'+
				'<a href="javascript:void(0)" onclick="delEditImg('+EDIT_IMG_IDX+')"">删除</a>'
				'</div>';
			$("#editPpThumb").append(imgHtml);
    	}
    }
    option.imgExts = ['jpg','jpeg','png'];
    
    var uploader = new AjaxUploadEx(option);
}
function delEditImg(idx){
	$("#editImg_"+idx).remove();
}

//新建印刷 
function addPrintPara(){
	$("#editTable").show();
	$('#editForm').form('clear');
	$('#editPpName').html('');
	$("#editPpId").val('');
	$("#editInsideName").val('');
	$("#editPpThumb").html('');
	
	$('#editPpSize').combobox('select',1);
	$("#editPpStyle").val('');
	$("#editPpMat").val('');
	$("#editPpTech").val('');

	$("#editPpType").combobox('select',1);
	$("#editPpPricing").combobox('select',10);
	
	
	$("#editBtn").show();
	$('#editDlg').window({
		title:'新建印刷商品',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#editDlg').window('move',{top:20,left:20});
	$('#editDlg').window('open');
}

// 编辑商品信息
function doEdit(){
	var ppNm = $('#editPpName').val();
	var desc = $("#editPpDesc").val();
	var ppId = $("#editPpId").val();
	var ppInNm =  $('#editInsideName').val();
	
	var ppSize = $("#editPpSize").combobox('getValue');	//	尺寸
	var ppStyle = $("#editPpStyle").val();	//	样式
	var ppMat =  $('#editPpMat').val();		//	材质
	var ppTech =  $('#editPpTech').val();	//	工艺
	
	var ppType = $("#editPpType").combobox('getValue');
	var ppPricing = $("#editPpPricing").combobox('getValue');
	
	var arrImgUrl = [];
	var arr = $("a.editImgUrl");
	for(var i=0; i<arr.length; i++){
		var imgUrl = $(arr[i]).attr('href');
		if(imgUrl && imgUrl.length>0){
			arrImgUrl.push(imgUrl);
		}
	}
	if(ppSize && ppSize.length>0
		&& ppStyle && ppStyle.length>0
		&& ppMat && ppMat.length>0
		&& ppTech && ppTech.length>0
		&& ppInNm && ppInNm.length>0
		&& ppNm && ppNm.length>0
		&& desc && desc.length>0) {
		// 默认新建
		var url = appPath+"/itbPrintParaWeb/addPrintPara.action";
		if(Number(ppId||'0')>0) {
			// 更新
			url = appPath+"/itbPrintParaWeb/updPrintPara.action";
		}
		var sendData = {
				
			"printParaInfo.pp_id": ppId||"",
			"printParaInfo.pp_name": ppNm,
			"printParaInfo.name": ppInNm,
			"printParaInfo.desc": desc || "",
			"printParaInfo.thumbs": JSON.stringify(arrImgUrl),
			"printParaInfo.pricing": Number(ppPricing||'10'),
			"printParaInfo.size_id": ppSize,
			"printParaInfo.style": ppStyle,
			"printParaInfo.mat": ppMat,
			"printParaInfo.tech": ppTech,
			
			"printParaInfo.type": Number(ppType||'0')
		};
	    $.post(url, sendData, function(data){  
			if (data == "ok") { 
				$.messager.alert('提示信息','提交成功','info');
				$('#editDlg').window('close');
				doQuery();
	        } else {
	        	$.messager.alert('提示信息','提交失败','info');
	        }
	    });
		
	} 
	else {
		$.messager.alert('提示信息','请填写完整信息','info');
	}
}
function cancelEdit(){
	$('#editDlg').window('close');
}

//查看/更新 印刷信息
function showDetail(id){
	$("#editTable").show();
	$('#editForm').form('clear');
	$("#editPpId").val(id);
	$('#editPpName').html('');
	$("#editInsideName").val('');
	$("#editPpThumb").html('');
	
	// 加载数据
	var url = appPath + "/itbPrintPara/getPrintParaInfoLst.action?pp_id="+ id;
	$.get(url,function(ret){
		if (ret && ret.length>0){
			var info = ret[0];
			$("#editPpName").val(info.pp_name||'');
			$("#editInsideName").val(info.name||'');
			$("#editPpDesc").val(info.desc||'');
			$("#editPpSize").combobox('select',Number(info.size_id||'0'));
			$("#editPpStyle").val(info.style||'');
			$("#editPpMat").val(info.mat||'');
			$("#editPpTech").val(info.tech||'');
			$("#editPpType").combobox('select',Number(info.type||'0'));
			$("#editPpPricing").combobox('select',Number(info.pricing||'0'));
			
			// 缩略图
			var arrImg = JSON.parse(info.thumbs||'[]');
			if(arrImg && arrImg.length>0) {
				for(var i=0; i<arrImg.length; i++){
					if(arrImg[i] && arrImg[i].length>0) {
						EDIT_IMG_IDX = Number(EDIT_IMG_IDX||0)+1;
			    		
			    		var showImg = arrImg[i]+'?x-oss-process=image/resize,m_pad,h_180,w_180,color_cccccc';
						var imgHtml = '<div style="margin:8px;" id="editImg_'+EDIT_IMG_IDX+'">'+
							'<a href="' + arrImg[i] + '" target="_blank" class="editImgUrl" style="margin-right:10px;">'+
							'<img src="'+showImg+'" style="display:inline;height:100px;width:100px">'+
							'</a>'+
							'<a href="javascript:void(0)" onclick="delEditImg('+EDIT_IMG_IDX+')"">删除</a>'
							'</div>';
						$("#editPpThumb").append(imgHtml);
					}
				}
			}
			
		}
	});
	
	$("#editBtn").show();
	$('#editDlg').window({
		title:'印刷详情/编辑',
		iconCls:'icon-edit',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$('#editDlg').window('move',{top:20,left:20});
	$('#editDlg').window('open');
}



//删除印刷信息
function delPrintPara(){
	var selectPrintPara=$("#printGrid").datagrid("getChecked");
	if(!selectPrintPara || selectPrintPara.length == 0){
		$.messager.alert('提示信息','请选择套餐！','warning');
		return;
	}
	for(var i=0; i<selectPrintPara.length; i++){
		if(Number(selectPrintPara[i].state||'0')==10){
			$.messager.alert('提示信息','不能删除[有效]套餐！','warning');
			return;
		}
	}
	
	$.messager.confirm("确认", "是否确认[删除]所选套餐？",
		function(r){
	        if (r) { 
				var ids = "";
				$.each(selectPrintPara, function(index, item){
					ids = ids + item.pp_id + ",";
				});
				var url = appPath+"/itbPrintParaWeb/delPrintPara.action?ids="+ids;
				$.post(url,function(data){
					if(data=="ok"){
						$.messager.alert('提示信息','删除成功','info');
						doQuery();
					}else{
						$.messager.alert('提示信息','删除失败','info');
					}
				});
	        }
		}
	);
}

/**
 * 获取请求信息
 */
function getQueryParam(){
	var queryObject = {};
	
	var findState = $("#queryPpState").combobox('getValue');
	var findType = $("#queryPpType").combobox('getValue');
	var findNm = $("#queryPpName").val();
	
	if(findState && Number(findState||'0')>0) queryObject.findPpState = findState;// 状态
	if(findType && Number(findType||'0')>0) queryObject.findPpType = findType;// 分类
	if(findNm && findNm.length>0) queryObject.findPpName = findNm;// 套餐名称
	//if(findMobile && Number(findMobile||'0')>0) queryObject.findFbMobile = findMobile;// 手机
	
	return queryObject;
}

/**
 * 查询数据
 */
function doQuery(){
	$("#printGrid").datagrid('unselectAll');
	$("#printGrid").datagrid('load', getQueryParam());
}

function fmtCreateTime(value, rowData, rowIndex){
	if(!value)return "";
	var s = new Date(value);
	return rowData.create_time=$.DateUtil.format(s,'yyyy/MM/dd hh:mm:ss');
}
